<template>
  <basic-container>
    <el-row :gutter="10">
      <el-col :span="drawerVisible ? 0 : 24">
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   ref="crud"
                   v-model="form"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   @row-del="rowDel"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad"
                   @tree-load="treeLoad">
          <template slot-scope="{row}" slot="menu">
            <el-row type="flex" class="row-bg" justify="center">
              <el-col :span="24">
                <el-tooltip class="item" effect="dark" content="权限配置" placement="bottom"
                            v-if="permission.api_scope_setting">
                  <div class="iconclick" @click="handleDataScope(row)"><span class="iconnew icon-quanxianfenpei"></span>
                  </div>
                </el-tooltip>
              </el-col>
            </el-row>
          </template>
          <template slot-scope="{row}" slot="source">
            <div style="text-align:center">
              <i :class="row.source"/>
            </div>
          </template>
        </avue-crud>
      </el-col>
      <el-col :span="24" v-if="drawerVisible">
        <div style="display: block;overflow: hidden;padding-bottom: 20px;">
          <h3 style="float:left;">{{ scopeMenuName }} — 接口权限配置</h3>
          <el-button style="float: right;padding:0;line-height: 30px;" type="text" @click="handleItem()">关闭</el-button>
        </div>
        <avue-crud :option="optionScope"
                   :data="dataScope"
                   :page="pageScope"
                   v-model="formScope"
                   :table-loading="scopeLoading"
                   ref="crudScope"
                   @row-del="rowDelScope"
                   @row-update="rowUpdateScope"
                   @row-save="rowSaveScope"
                   :before-open="beforeOpenScope"
                   @search-change="searchChangeScope"
                   @search-reset="searchResetScope"
                   @selection-change="selectionChangeScope"
                   @current-change="currentChangeScope"
                   @size-change="sizeChangeScope"
                   @on-load="onLoadScope">
          <template slot="menuLeft">
            <el-button size="small" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <el-button
              size="small"
              icon="el-icon-delete"
              plain
              @click="handleDeleteScope">删 除
            </el-button>
          </template>
          <template slot-scope="{row}"
                    slot="scopeType">
            <el-tag>{{ row.scopeTypeName }}</el-tag>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-row type="flex" class="row-bg" justify="center">
              <el-col :span="6">
                <el-tooltip class="item" effect="dark" content="详情" placement="bottom">
                  <div class="iconclick" @click="openView(scope.row,scope.index)"><span
                    class="iconnew icon-chakan"></span></div>
                </el-tooltip>
              </el-col>
              <el-col :span="6">
                <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
                  <div class="iconclick" @click="openEdit(scope.row,scope.index)"><span
                    class="iconnew icon-bianji"></span></div>
                </el-tooltip>
              </el-col>
              <el-col :span="6">
                <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                  <div class="iconclick" @click="rowDelScope(scope.row)"><span
                    class="iconnew icon-tubiaozhizuo-"></span></div>
                </el-tooltip>
              </el-col>
            </el-row>
          </template>
        </avue-crud>
      </el-col>
    </el-row>
  </basic-container>
</template>

<script>
import { add, getLazyMenuList, getMenu, remove, update } from '@/api/system/menu'
import { addApiScope, getListApiScope, getMenuApiScope, removeApiScope, updateApiScope } from '@/api/system/scope'
import { mapGetters } from 'vuex'
import { datascopeOption } from '@/const/authority/datascope'
import { optionScope } from '@/const/authority/apiscope'

export default {
  data() {
    return {
      form: {},
      selectionList: [],
      query: {},
      loading: true,
      parentId: 0,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      drawerVisible: false,
      direction: 'rtl',
      scopeLoading: false,
      scopeMenuId: 0,
      scopeMenuName: '菜单',
      menu: true,
      option: datascopeOption,
      data: [],
      formScope: {},
      selectionListScope: [],
      pageScope: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      optionScope,
      dataScope: []
    }
  },

  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.menu_add, false),
        viewBtn: this.vaildData(this.permission.menu_view, false),
        delBtn: this.vaildData(this.permission.menu_delete, false),
        editBtn: this.vaildData(this.permission.menu_edit, false)
      }
    },
    ids() {
      let ids = []
      this.selectionList.forEach(ele => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
    scopeIds() {
      let ids = []
      this.selectionListScope.forEach(ele => {
        ids.push(ele.id)
      })
      return ids.join(',')
    }
  },
  methods: {
    handleItem: function (row) {
      if (row) {
        this.drawerVisible = row
        this.page2.currentPage = 1
        this.getPage2(this.page2)
      } else {
        this.drawerVisible = false
      }
    },
    openView(row, index) {
      this.$refs.crudScope.rowView(row, index)
    },
    openEdit(row, index) {
      this.$refs.crudScope.rowEdit(row, index)
    },
    handleAdd() {
      this.$refs.crudScope.rowAdd()
    },
    // 菜单管理模块
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }, error => {
        window.console.log(error)
        loading()
      })
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }, error => {
        window.console.log(error)
        loading()
      })
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id)
        })
        .then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
    },
    searchReset() {
      this.query = {}
      this.parentId = 0
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.parentId = ''
      this.page.currentPage = 1
      this.onLoad(this.page, params)
      done()
    },
    selectionChange(list) {
      this.selectionList = list
    },
    selectionClear() {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids)
        })
        .then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.$refs.crud.toggleSelection()
        })
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getMenu(this.form.id).then(res => {
          this.form = res.data.data
        })
      }
      done()
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    refreshChange() {
      this.onLoad(this.page, this.query)
    },
    onLoad(page, params = {}) {
      this.loading = true
      getLazyMenuList(this.parentId, Object.assign(params, this.query)).then(res => {
        this.data = res.data.data
        this.loading = false
        this.selectionClear()
      })
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id
      getLazyMenuList(parentId).then(res => {
        resolve(res.data.data)
      })
    },
    // 数据权限模块
    handleDataScope(row) {
      this.drawerVisible = true
      this.scopeMenuId = row.id
      this.scopeMenuName = row.name
      this.onLoadScope(this.pageScope)
    },
    handleDrawerClose(hide) {
      hide()
    },
    rowSaveScope(row, done, loading) {
      row = {
        ...row,
        menuId: this.scopeMenuId
      }
      addApiScope(row).then(() => {
        this.onLoadScope(this.pageScope)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }, error => {
        window.console.log(error)
        loading()
      })
    },
    rowUpdateScope(row, index, done, loading) {
      row = {
        ...row,
        menuId: this.scopeMenuId
      }
      updateApiScope(row).then(() => {
        this.onLoadScope(this.pageScope)
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }, error => {
        window.console.log(error)
        loading()
      })
    },
    rowDelScope(row) {
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeApiScope(row.id)
        })
        .then(() => {
          this.onLoadScope(this.pageScope)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
    },
    handleDeleteScope() {
      if (this.selectionListScope.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeApiScope(this.scopeIds)
        })
        .then(() => {
          this.onLoadScope(this.pageScope)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.$refs.crudScope.toggleSelection()
        })
    },
    beforeOpenScope(done, type) {
      if (['edit', 'view'].includes(type)) {
        getMenuApiScope(this.formScope.id).then(res => {
          this.formScope = res.data.data
        })
      }
      done()
    },
    searchResetScope() {
      this.onLoadScope(this.pageScope)
    },
    searchChangeScope(params, done) {
      this.onLoadScope(this.pageScope, params)
      done()
    },
    selectionChangeScope(list) {
      this.selectionListScope = list
    },
    currentChangeScope(currentPage) {
      this.pageScope.currentPage = currentPage
    },
    sizeChangeScope(pageSize) {
      this.pageScope.pageSize = pageSize
    },
    onLoadScope(page, params = {}) {
      this.scopeLoading = true
      const values = {
        ...params,
        menuId: this.scopeMenuId
      }
      getListApiScope(page.currentPage, page.pageSize, Object.assign(values, this.query)).then(res => {
        const data = res.data.data
        this.pageScope.total = data.total
        this.dataScope = data.records
        this.selectionListScope = []
        this.scopeLoading = false
      })
    }
  }
}
</script>
